package com.wwwarehouse.taskcenter.fragment.job_point.step5;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.eventbus_event.BackListenerEvent;
import com.wwwarehouse.common.fragment.CommonBasePagerFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.job_point.AddJobPointStep5HavedUnitResponseBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;
import com.wwwarehouse.taskcenter.eventbus_event.TaskPointCardEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * @创建者 chenchao.
 * @创建时间 2017/10/25 18:53
 * @描述 ${TODO}
 */

public class ChooseJobUnitHavedUnitPagerFragment5 extends CommonBasePagerFragment {

    public static final int REQUEST_CODE = 10004;

    private String jobPointUkid,warehouseUkid;
    private ArrayList<AddJobPointStep5HavedUnitResponseBean> beans;
    private List<String> selectList;
    private static final int REQUEST_SCANCODE_SAVESTEP = 10001,REQUEST_SCANCODE_SAVEDATA=10002;


    @Override
    public void onRefreshListener() {
    }


    @Override
    public void onLoadError(String s) {

    }


    @Override
    public void setTitle() {
        if (peekFragment() instanceof ChooseJobUnitHavedUnitPagerFragment5) {
            mActivity.setTitle("" + getString(R.string.new_task_step5_judege_unit));
        }
    }

    @Override
    public void requestDatas() {
        super.requestDatas();

        jobPointUkid = getArguments().getString("jobPointUkid");
        warehouseUkid = getArguments().getString("warehouseUkid");

        showConfirmButton();
        RelativeLayout relativeLayout = getConfirmLayout();
        relativeLayout.removeAllViews();

        selectList = new LinkedList<>();


        mAddBtn = new Button(mActivity);
        mSureBtn = new Button(mActivity);

        //新增规则
        RelativeLayout.LayoutParams addParams = new RelativeLayout.LayoutParams(ConvertUtils.dip2px(mActivity, 55), ConvertUtils.dip2px(mActivity, 55));
        addParams.setMargins(0, 0, 0, 10);
        mAddBtn.setLayoutParams(addParams);
        mAddBtn.setBackground(getResources().getDrawable(R.drawable.cir_btn_add_blue_selector));
        mAddBtn.setText(getString(R.string.new_task_new));
        mAddBtn.setTextColor(getResources().getColor(R.color.common_color_c3_ffffff));
        mAddBtn.setTextSize(14);

        //确定
        RelativeLayout.LayoutParams confirmParams = new RelativeLayout.LayoutParams(ConvertUtils.dip2px(mActivity, 55), ConvertUtils.dip2px(mActivity, 55));
        confirmParams.setMargins(ConvertUtils.dip2px(mActivity, 100), 0, 0, 10);
        mSureBtn.setLayoutParams(confirmParams);
        mSureBtn.setBackground(getResources().getDrawable(R.drawable.cir_btn_gray_blue_selector));
        mSureBtn.setText(getString(R.string.new_task_save));
        mSureBtn.setTextColor(getResources().getColor(R.color.common_color_c3_ffffff));
        mSureBtn.setTextSize(14);

        mSureBtn.setEnabled(false);

        relativeLayout.addView(mAddBtn);
        relativeLayout.addView(mSureBtn);

        mSureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });
        mSureBtn.setEnabled(false);

        mAddBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("jobPointUkid", jobPointUkid);
                bundle.putString("warehouseUkid", warehouseUkid);
                ChooseJobUnitAddFirstpageFragment5 protectTaskUnitFragment = new ChooseJobUnitAddFirstpageFragment5();
                protectTaskUnitFragment.setArguments(bundle);
                pushFragment(protectTaskUnitFragment);
            }
        });

        requestHttp();
        EventBus.getDefault().register(this);

    }


    private Button mAddBtn;
    private Button mSureBtn;

    @Override
    public void onDownPull() {
        ((BaseCardDeskActivity)mActivity).setTitleBt1Text("完成此步");
        ((BaseCardDeskActivity)mActivity).showTitleBt1();
        ((BaseCardDeskActivity)mActivity).downPull_3();
        if( BaseApplication.sp.getBooleanValue("isCanfinish",false)){
            ((BaseCardDeskActivity)mActivity).setTitleBt1Enable(true);
        }else{
            ((BaseCardDeskActivity)mActivity).setTitleBt1Enable(false);
        }
    }

    @Override
    public void titleBt1Click() {
        if(peekFragment() instanceof ChooseJobUnitHavedUnitPagerFragment5 && BaseApplication.sp.getBooleanValue("isCanfinish",false)){
            saveStep();
        }
    }

    /**
     * 保存步骤
     */

    public void saveStep(){
        Map<String,String> map  = new HashMap<>();
        map.put("jobPointUKid",jobPointUkid);
        map.put("step","5");
        /**
         * jobPointUKid	作业点ukid	number	@mock=100000110
         step	步骤，第二步，第四步，第五步需要调用	number	@mock=2
         */
        NoHttpUtils.httpPost(TaskCenterConstant.URL_JOBPOINT_SAVESTEP,map,myResponse,REQUEST_SCANCODE_SAVESTEP);
    }

    /**
     * 查询类目
     */
    private void requestHttp() {
        Map<String, Object> map = new HashMap<>();
        map.put("jobPointUkid", jobPointUkid);
        loadData(TaskCenterConstant.URL_ADD_JOBPOINT_STEP5_GETALLBYNAME, map, REQUEST_CODE);
    }

    /**
     * 保存数据
     */
    public void saveData() {
        Map<String, Object> map = new HashMap<>();
        /**
         * jbUnitUkids	作业单元集合	array<number>	@mock=$order(52119207219161000,52118309276557000)
         jobPointUkid	作业点ukid	number	@mock=100000110
         */
        List<Object> list = new LinkedList<>();

        for (String content : selectList) {
            list.add(Long.parseLong(content));
        }

        try {
            map.put("jobPointUkid", Long.parseLong(jobPointUkid) );
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("jbUnitUkids", list);

        NoHttpUtils.httpPost(TaskCenterConstant.URL_ADD_JOBPOINT_STEP5_BINDNEWJOBPIONT, map, myResponse, REQUEST_SCANCODE_SAVEDATA);
        showProgressDialog();
    }

    NoHttpUtils.OnResponseListener myResponse = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int i) {
            switch (i){
                case REQUEST_SCANCODE_SAVEDATA:
                    if ("0".equals(commonClass.getCode())) {
                        BaseApplication.sp.putBooleanValue("isCanfinish",true);
                        toast(commonClass.getMsg());
                    }else{
                        toast("" + commonClass.getMsg());
                    }
                    break;

                case REQUEST_SCANCODE_SAVESTEP:
                    if("0".equals(commonClass.getCode())){
                        TaskPointCardEvent event = new TaskPointCardEvent();
                        event.setFinish5(true);
                        BaseApplication.sp.putBooleanValue("isCanfinish",false);
                        EventBus.getDefault().post(event);
                        ((BaseCardDeskActivity)mActivity).cleanBackStackWithLeftNumber(1);
                    }else{
                        ToastUtils.showToast("" + commonClass.getMsg());
                    }
                    break;
                default:
                    break;
            }

        }

        @Override
        public void onFailed(String s, int i) {
        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };



    @Override
    public void onLoadSuccess(String s, int i) {
        beans = (ArrayList) JSON.parseArray(s, AddJobPointStep5HavedUnitResponseBean.class);
        if (beans != null) {
            initPager();
        } else {
            LogUtils.showErrLog("解析错误");
        }
    }

    private void initPager() {
        Bundle bundle = new Bundle();
        bundle.putString("jobPointUkid", jobPointUkid);
        try {
            setData(beans.size(), 2, "com/wwwarehouse/taskcenter/fragment/job_point/step5/ChooseJobUnitHavedUnitDetailFragment5", bundle, beans);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.showErrLog("error:" + e.getMessage());
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(AddJobPointStep5HavedUnitResponseBean bean) {
        if (selectList.contains(bean.getJbUnitUkid())) {
            Iterator<String> iterator = selectList.iterator();
            while (iterator.hasNext()){
                if((""+bean.getJbUnitUkid()).equals(iterator.next())){
                    iterator.remove();
                }
            }
        } else {
            selectList.add(bean.getJbUnitUkid());
        }

        if (selectList == null || selectList.size() == 0) {
            mSureBtn.setEnabled(false);
        }else{
            mSureBtn.setEnabled(true);
        }


    }

    /**
     *
     * if (peekFragment() instanceof ChooseJobUnitHavedUnitPagerFragment5 && bean instanceof BackListenerEvent ) {
     if (TextUtils.isEmpty(oppositeUrl)) {
     popFragment();
     } else {
     ((BaseCardDeskActivity) mActivity).cleanBackStack();
     }
     }
     */
    public void onEventMainThread(BackListenerEvent event) {
        if (peekFragment() instanceof ChooseJobUnitHavedUnitPagerFragment5 && "ChooseJobUnitHavedUnitPagerFragment5".equals(event.getMsg())) {
            ((BaseCardDeskActivity) mActivity).cleanBackStackWithLeftNumber(1);
        }
    }

}
